package com.example.servletdemo.servlet.user;

import com.example.servletdemo.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.设置编码
        req.setCharacterEncoding("utf-8");
        //2.获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //3.封装user对象
        User loginUser = new User();
        loginUser.setUsername(username);
        loginUser.setPassword(password);

        //4.调用UserDao的login方法

        //5.判断user
        if(!loginUser.getUsername().equals("admin")){
            System.out.println("登录失败");
            //登录失败
            resp.sendRedirect("/loginFail.jsp");
        }else{
            //登录成功
            System.out.println("登录成功");

            HttpSession session = req.getSession();
            session.setAttribute("user",loginUser);

            req.setAttribute("user",loginUser);
            //转发
//            req.getRequestDispatcher("/main.jsp").forward(req,resp);
            //重定向
            resp.sendRedirect("/main.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
